﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Technician;

public class Recheck(IRepository<Exam, Guid> examRepository, IExamEventService examEventService, ICurrentUserOrganization currentUserOrganization, IRepository<ApplicationUser, Guid> userRepository, IRepository<BusinessObjects.Exams.Report, Guid> reportRepository) : WorkflowBase, IRecheck, ITransientDependency
{
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;
    private readonly IExamEventService _examEventService = examEventService;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<ApplicationUser, Guid> _userRepository = userRepository;
    private readonly IRepository<BusinessObjects.Exams.Report, Guid> _reportRepository = reportRepository;
    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        const string key = "Input";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Dictionary<string, object> data)
        {
            if (Guid.TryParse(data.GetValueOrDefault("examId")?.ToString(), out Guid examId))
            {
                var exam = await _examRepository.GetAsync(examId);
                exam.ExamStatus = ExamStatus.Exam;
                exam.ExamQueuing.Status = ExamQueuingStatus.Check;
                exam.ExamTime = Clock.Now;
                //检查技师
                exam.ExamOperator = await _userRepository.GetAsync(_currentUserOrganization.UserId);
                //删除报告信息
                if (exam.Report != null)
                {
                    await _reportRepository.DeleteAsync(exam.Report);
                    exam.Report = null;
                }
                var reason = data.GetValueOrDefault("reason") as string;
                await _examEventService.AddExamEventAsync(exam, "重新检查", reason);
                //处理逻辑
                return new WorkflowOutput
                {
                    Success = true,
                    Data = exam.Oid
                };
            }
        }
        return new WorkflowOutput
        {
            Success = false,
            Error = "未找到Exam对象",
        };
    }
}
